<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryObj.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="changeValue"
        />
        <!-- 树形组件
          check-strictly: 开启不严格相关选中。可以单独选中父节点！
        -->
        <!--  -->
        <!-- show-checkbox -->
        <el-tree
          ref="tree"
          node-key="id"
          :data="depList"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          highlight-current
          check-strictly
          @current-change="hCurrentChange"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button v-allow="'excel_inport'" size="mini" @click="showExcelDialog=true">excel导入</el-button>

          <!-- 这个按钮显示的条件是： vuex 中保存的points中有 excel_export  -->
          <!-- {{ $store.state.user.userInfo.roles.points }} -->
          <!-- v-if="$store.state.user.userInfo.roles.points.includes('excel_export')" -->
          <el-button
            v-allow="'excel_export'"
            size="mini"
            @click="hExport"
          >excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="employList">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{row}">
              <img v-if="row.staffPhoto" style="width:30px" :src="row.staffPhoto">
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column label="聘用形式">
            <template v-slot="{row}">
              <!-- 形式：{{ row.formOfEmployment }} -->
              <span v-if="row.formOfEmployment===1">正式</span>
              <span v-else-if="row.formOfEmployment===2">非正式</span>
              <span v-else>未知</span>
            </template>
          </el-table-column>

          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template #default="{row}">
              <el-button size="mini" type="text" @click="$router.push('/employee/detail/' +row.id)">查看</el-button>
              <el-button size="mini" type="text" @click="hAssignRole(row.id)">角色</el-button>
              <el-button size="mini" type="text">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->

        <el-row type="flex" style="height:60px" align="middle" justify="end">
          <!-- 放置分页组件
        total: 总数据条数
        page-size: 每页几条数据
        @current-change： 页码变化（用户点击）执行，自动传入当前的页码
        @current-change="hCurrentChage"
        @size-change="hSizeChange"
        -->
          <el-pagination
            :current-page="queryObj.page"
            :page-sizes="[3,5,7]"
            :background="true"
            layout="total,prev, pager, next, sizes"
            :total="total"
            :page-size="queryObj.pagesize"
            @current-change="changePage"
            @size-change="hSizeChange"
          />
        </el-row>
      </div>
    </div>
    <importExcel
      :show-excel-dialog.sync="showExcelDialog"
      :update-employees="loadDepartment"
    />

    <assignRole ref="refRole" :cur-id="curId" :show-role-dialog.sync="showRoleDialog" />
  </div>
</template>

<script>
import { getEmployeeList, exportEmployee } from '@/api/employee'
import { getDepartment } from '@/api/department'
import { arr2tree } from '@/utils/index'
import FileSaver from 'file-saver'
import importExcel from './components/import-excel.vue'
import assignRole from './components/assignRole.vue'

export default {
  name: 'Employee',
  components: {
    importExcel, assignRole
  },
  data() {
    return {
      curId: -1,
      showExcelDialog: false,
      showRoleDialog: false,
      total: 0,
      employList: [],
      queryObj: {
        page: 1,
        pagesize: 10,
        keyword: null,
        departmentId: 1
      },
      defaultProps: { label: 'name', children: 'children' },
      depList: [
        // { name: '传智教育', children: [{ name: '总裁办' }] }
      ]
    }
  },
  created() {
    this.loadDepartment()
  },
  methods: {
    changeValue() {
      this.queryObj.page = this.page
      this.loadDepartment()
      // 防抖处理
      clearTimeout(this.timer) // 清理上一次的定时器
      this.timer = setTimeout(() => {
        this.queryObj.page = 1
        this.getEmployeeList()
      }, 300)
    },
    hSizeChange(pages) {
      this.queryObj.pagesize = pages
      this.queryObj.page = 1
      this.loadDepartment()
    },
    changePage(newPage) {
      this.queryObj.page = newPage
      this.loadDepartment()
    },
    hAssignRole(id) {
      // 1.保存 id
      this.curId = id
      // 2.显示弹窗
      this.showRoleDialog = true
      // 3.调用子组件方法，获取当前员工信息
      this.$nextTick(() => {
        this.$refs.refRole.getRolesById()
      })
    },
    addEmployee() {
      this.$router.push('/employee/detail')
    },
    async hExport() {
      const res = await exportEmployee()
      // console.log(res)
      FileSaver.saveAs(res, '员工信息表.xlsx') // 下载文件
    },
    async loadDepartment() {
      const res = await getDepartment()
      const rs = arr2tree(res.data, 0)
      this.queryObj.total = res.data.length
      this.depList = rs
      // 第一个节点
      const id = rs[0].id
      // 记录id
      this.queryObj.departmentId = id

      this.$nextTick(() => {
        // this.$refs.tree.setCheckedKeys([id])
        this.$refs.tree.setCurrentKey(id)
      })
      // 发一次请求
      this.loadEmployment()

      // const rs = arr2tree(res.data, 1)
      // this.depList = [{ name: '传智教育', children: rs }]
      // this.depList = rs
    },
    async loadEmployment() {
      // console.log('查询条件是', this.queryObj)
      // 调用api
      // axios在发请求的时候，如果你的参数值为null，它会丢弃这个参数
      const res = await getEmployeeList(this.queryObj)
      // console.log(res)
      this.total = res.data.total
      this.employList = res.data.rows
    },
    hCurrentChange(data, node) {
      // console.log(data, node)
      // 记录id
      this.queryObj.departmentId = data.id
      // 发请求拿到对应的部门的信息
      this.loadEmployment()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>

<style>
/* .el-tree--highlight-current .el-tree-node.is-checked > .el-tree-node__content {
    color: #276FFB;
    background-color: #f0f4ff;
} */
</style>
